import { HttpAdapterHost, NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
import { AllExceptionFilter } from './common/filters/all-exception.filter';
import { GlobalInterceptor } from './common/interceptor/global.interceptor';
import { Logger, ValidationPipe } from '@nestjs/common';
import { JwtAuthGuard } from './auth/jwt-auth.guard';
import helmet from 'helmet';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

async function bootstrap() {
  const logger = new Logger('bootstrap');
  const app = await NestFactory.create(AppModule);

  // Security Middleware
  app.use(helmet());
  app.enableCors();

  const configService = app.get(ConfigService);

  // Swagger API Documentation (only in non-production environments)
  if (configService.get('NODE_ENV') !== 'prod') {
    const config = new DocumentBuilder()
      .setTitle('NestJS Starter API')
      .setDescription('The NestJS Starter API description')
      .setVersion('1.0')
      .addBearerAuth()
      .build();
    const document = SwaggerModule.createDocument(app, config);
    SwaggerModule.setup('api-docs', app, document);
  }

  const port: number = configService.get('PORT') ?? 3000;
  app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
    }),
  );
  const reflector = app.get(Reflector);
  app.useGlobalGuards(new JwtAuthGuard(reflector));
  app.useGlobalFilters(new AllExceptionFilter(app.get(HttpAdapterHost)));
  app.useGlobalInterceptors(new GlobalInterceptor(reflector));
  await app.listen(port);
  logger.log(`Server is running on port ${port}`);
  if (configService.get('NODE_ENV') !== 'prod') {
    logger.log(
      `API documentation available at http://localhost:${port}/api-docs`,
    );
  }
  logger.log(`當前環境：${process.env.NODE_ENV}`);
}
bootstrap();
